import logging
import random
import re
import time
import coloredlogs
import pythoncom
from docx import Document
from PyQt5.QtCore import QTimer, pyqtSlot
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QTabWidget, QPushButton, QMessageBox, QLineEdit, QTextEdit, QTableWidget, QTableWidgetItem, \
    QHeaderView
import json
import threading
import datetime
import os
from playwright.sync_api import Playwright
from playwright.sync_api import sync_playwright
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QTextEdit, QPushButton, QLabel)
from PyQt5.QtCore import pyqtSignal, QUrl, Qt, QEvent
from PyQt5.QtGui import QColor, QPalette, QDragEnterEvent, QDropEvent
from PyQt5.QtWidgets import (QApplication, QWidget, QVBoxLayout, QSplitter, QTextEdit, QPushButton, QLabel)
from PyQt5.QtCore import pyqtSignal, QUrl, Qt, QEvent
from PyQt5.QtGui import QColor, QPalette, QDragEnterEvent, QDropEvent
document = Document()
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
logging.getLogger("urllib3").setLevel(logging.INFO)
coloredlogs.install(level='INFO', logger=logging.getLogger(),
                    level_styles={'info': {'color': 'green'}})
current_date = datetime.datetime.now().strftime('%Y.%m.%d')
with open(f'output_logs/all_model.txt', "a+", encoding="utf-8") as f4:
    overartical = f4.readlines()
    overartical = [title.strip() for title in overartical]

random_number = random.randint(1, 10) / 10
data = {}

class FolderDropWidget(QWidget):
    folderDropped = pyqtSignal(str)  # 发射单个路径
    foldersDropped = pyqtSignal(list)  # 发射文件夹列表

    def __init__(self, parent=None):
        super(FolderDropWidget, self).__init__(parent)
        self.folderPaths = []
        self.initUI()

    def initUI(self):
        self.setAcceptDrops(True)
        self.layout = QVBoxLayout(self)

        # 创建两个子窗口
        self.displayWidget = QWidget(self)
        self.dragWidget = QWidget(self)

        # 设置 displayWidget 的布局
        self.displayLayout = QVBoxLayout(self.displayWidget)
        self.text_edit = QTextEdit()
        self.text_edit.setReadOnly(False)  # 设置为可编辑
        self.displayLayout.addWidget(self.text_edit)

        self.saveButton = QPushButton("开始上传")
        self.saveButton.clicked.connect(self.saveEdits)
        self.displayLayout.addWidget(self.saveButton)

        self.displayWidget.setAutoFillBackground(True)
        palette = self.displayWidget.palette()
        palette.setColor(QPalette.Window, QColor('#fff0ff'))  # 设置背景颜色
        self.displayWidget.setPalette(palette)

        # 设置 dragWidget 的布局
        self.dragLayout = QVBoxLayout(self.dragWidget)
        self.label = QLabel("将需要新添加的文件夹拖放至此窗口")
        self.dragLayout.addWidget(self.label)

        self.dragWidget.setAutoFillBackground(True)
        palette = self.dragWidget.palette()
        palette.setColor(QPalette.Window, QColor('#e0f7ff'))  # 设置背景颜色
        self.dragWidget.setPalette(palette)

        # 将两个子窗口添加到主布局
        self.splitter = QSplitter(Qt.Vertical)
        self.splitter.addWidget(self.displayWidget)
        self.splitter.addWidget(self.dragWidget)
        self.layout.addWidget(self.splitter)
        # 连接拖放信号
        self.dragWidget.installEventFilter(self)

    def dragEnterEvent(self, event: QDragEnterEvent):
        if event.mimeData().hasUrls():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event: QDropEvent):
        urls = event.mimeData().urls()
        for url in urls:
            folderPath = QUrl(url.toString()).toLocalFile()
            self.folderPaths.append(folderPath)
            self.text_edit.append(folderPath)  # 添加处理后的路径
        self.foldersDropped.emit(self.folderPaths)  # 发射整个路径列表

    def saveEdits(self):
        # 从文本编辑器获取所有文本，更新路径列表
        global data
        editedPaths = self.text_edit.toPlainText().split('\n')
        self.folderPaths = [QUrl(path).toLocalFile() if path.startswith('file:///') else path for path in editedPaths]
        # 检查路径是否存在，不存在则删除
        self.folderPaths = [path for path in self.folderPaths if os.path.exists(path)]
        # 更新文本编辑器内容
        self.text_edit.setPlainText('\n'.join(self.folderPaths))
        print("路径已更新:")
        for path in self.folderPaths:
            print(path)
        data['folderPath'] = self.folderPaths
        main()
    def eventFilter(self, source, event):
        if event.type() == QEvent.DragEnter:
            if event.mimeData().hasUrls() and source == self.dragWidget:
                event.accept()
                return True
            else:
                event.ignore()
                return False
        elif event.type() == QEvent.Drop and source == self.dragWidget:
            urls = event.mimeData().urls()
            folderPaths = [QUrl(url.toString()).toLocalFile() for url in urls]
            self.text_edit.clear()  # 清除显示窗口内容
            for folderPath in folderPaths:
                self.text_edit.append(folderPath)  # 将拖放的文件夹路径添加到显示窗口
            self.foldersDropped.emit(folderPaths)  # 发射文件夹列表信号
            self.label.setText("拖放成功，请继续拖放")
            return True
        return super(FolderDropWidget, self).eventFilter(source, event)

class MyApp(QWidget):
    def __init__(self):
        super().__init__()
        self.count = 0
        self.num = 0
        self.timegap = 0
        self.gettitle = ""
        self.status = "running"
        self.script_started = False  # 新增的行
        self.folderPath = ""  # 添加一个成员变量来存储文件夹路径
        self.initUI()

    def update_variables(self, count, num, timegap, gettitle, status):
        self.count = count
        self.num = num
        self.timegap = timegap
        self.gettitle = gettitle
        self.status = status
        self.update_table()  # 在变量更新时更新表格

    def start_script(self):
        self.script_started = True
        self.thread_it(main)()
        # 创建一个定时器，每秒更新一次表格
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_table)
        self.timer.start(1000)  # 参数是更新间隔，以毫秒为单位，1000毫秒等于1秒

    def initUI(self):
        global data
        self.setWindowTitle("模型上传助手3.0")
        self.setWindowIcon(QIcon('logo_wen.ico'))
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        self.resize(600, 600)
        self.main_running = False

        # 创建一个选项卡小部件
        self.tab_widget = QTabWidget()
        self.layout.addWidget(self.tab_widget)

        # 创建两个选项卡
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        # 将选项卡添加到选项卡小部件中
        self.tab_widget.addTab(self.tab1, "运行日志")
        self.tab_widget.addTab(self.tab2, "软件设置")
        self.tab_widget.addTab(self.tab3, "选择文件夹路径并且上传")  # 添加新的选项卡标签

        self.folder_drop_widget = FolderDropWidget()
        self.tab3.layout = QVBoxLayout(self.tab3)
        self.tab3.layout.addWidget(self.folder_drop_widget)


        self.tab3.setLayout(self.tab3.layout)
        # 为 '运行日志' 选项卡创建一个表格
        self.table = QTableWidget(self.tab1)
        self.table.setRowCount(15)  # 设置行数
        self.table.setColumnCount(4)  # 设置列数
        self.table.setHorizontalHeaderLabels(["ID", "运行账号", "今日上传", "运行状态"])
        self.table.horizontalHeader().setStyleSheet("QHeaderView::section { background-color: #cde6c7 }")

        # 隐藏行号
        self.table.verticalHeader().setVisible(False)

        # 设置列宽
        self.table.setColumnWidth(0, 10)  # 设置 "ID" 列宽为50
        self.table.setColumnWidth(1, 200)  # 设置 "运行账号" 列宽为200
        self.table.setColumnWidth(3, 200)  # 设置 "运行状态" 列宽为200

        # 设置列宽以填满表格
        header = self.table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)

        # 用数据填充表格
        for i in range(zhanghaonum):
            item_id = QTableWidgetItem(str(i + 1))
            item_id.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(i, 0, item_id)

            item_account = QTableWidgetItem(zhanghaolist[i])
            item_account.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(i, 1, item_account)

        # 更新 "今日上传" 列和 "运行状态" 列
        self.update_table()

        # 添加 '启动脚本' 按钮
        self.run_script_button = QPushButton('运行启动', self.tab1)
        self.run_script_button.clicked.connect(self.start_script)

        # 设置选项卡的布局
        self.tab1.layout = QVBoxLayout(self.tab1)
        self.tab1.layout.addWidget(self.table)
        self.tab1.layout.addWidget(self.run_script_button)
        self.tab1.setLayout(self.tab1.layout)

        # 设置表格的拉伸系数
        self.tab1.layout.setStretchFactor(self.table, 1)
        self.tab1.layout.setStretchFactor(self.run_script_button, 0)

        self.tab2.layout = QVBoxLayout(self.tab2)

        # 读取 json 文件
        filename = 'AccountData/configuration.json'
        with open(filename, 'r') as f:
            data = json.load(f)

        # 用于保存 QLineEdit 和 QTextEdit 控件的字典
        self.widgets = {}

        # 对于每个配置项，创建一个 QLabel 和一个 QLineEdit 或 QTextEdit
        for key, value in data.items():
            # 创建 QLabel
            label = QLabel()
            label.setText(key)
            self.tab2.layout.addWidget(label)

            # 判断值的类型
            if isinstance(value, list):
                # 创建 QTextEdit
                widget = QTextEdit()
                widget.setText(', '.join(value))
            else:
                # 创建 QLineEdit
                widget = QLineEdit()
                widget.setText(str(value))
            self.tab2.layout.addWidget(widget)
            # 将 QLineEdit 或 QTextEdit 保存到字典中
            self.widgets[key] = widget

        # 创建按钮
        self.getcookieplay_button = QPushButton("获取cookie", self.tab2)
        self.getcookieplay_button.clicked.connect(self.getcookieplay)
        self.tab2.layout.addWidget(self.getcookieplay_button)

        self.checkcookieplay_button = QPushButton("查看cookie", self.tab2)
        self.checkcookieplay_button.clicked.connect(lambda: self.thread_it(checkmain)())
        self.tab2.layout.addWidget(self.checkcookieplay_button)

        self.save_button = QPushButton("保存配置", self.tab2)
        self.save_button.clicked.connect(self.save_data)
        self.tab2.layout.addWidget(self.save_button)

        self.tab2.setLayout(self.tab2.layout)

    def print_folder_paths(self):
        print("打印文件夹路径按钮被点击")
        if self.folder_drop_widget.folderPaths:
            for folder in self.folder_drop_widget.folderPaths:
                print(folder)
        else:
            print("文件夹列表为空")

    def handle_folders_dropped(self, folders):
        print("Received folders:", folders)
        # 在这里添加处理文件夹路径的代码
        for folder in folders:
            # 处理每个文件夹路径
            print(folder)
    def update_table(self):
        # 更新 "今日上传" 列和 "运行状态" 列
        for i in range(zhanghaonum):
            # 获取当前日期
            current_date = datetime.datetime.now().strftime('%Y.%m.%d')  # 修改这里

            # 生成文件路径
            filename = f'output_logs/log/{current_date}_{zhanghaolist[i]}.txt'

            # 如果文件存在，则读取文件中的标题数量
            if os.path.exists(filename):
                with open(filename, 'r') as f:
                    self.count = len(f.readlines())
            else:
                self.count = 0  # 如果文件不存在，则将数量设为0

            # 更新 "今日上传" 列
            item_upload = QTableWidgetItem(str(self.count))
            item_upload.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(i, 2, item_upload)

            # 更新 "运行状态" 列
            account = zhanghaolist[i]
            if account in account_status:
                status = account_status[account]
                item_status = QTableWidgetItem(status)
            else:
                item_status = QTableWidgetItem("状态未知")

            item_status.setTextAlignment(Qt.AlignCenter)
            self.table.setItem(i, 3, item_status)

    def thread_it(self, func, *args):
        if func.__name__ == 'main' and self.main_running:
            logging.error(f"点击运行")

        elif func.__name__ == 'main':
            self.main_running = True

        def wrapped_func():
            t = threading.Thread(target=func, args=args)
            t.daemon = True
            t.start()

        return wrapped_func

    @pyqtSlot()
    def save_data(self):
        global data
        for key, widget in self.widgets.items():
            if isinstance(data[key], list):
                data[key] = widget.toPlainText().split(', ')
            else:
                data[key] = widget.text()

        with open('AccountData/configuration.json', 'w') as f:
            json.dump(data, f)
        QMessageBox.information(self, "消息", "保存成功")

    def getcookieplay(self):
        # 实现你的 getcookieplay 函数
        with sync_playwright() as playwright:
            getcookie(playwright)
        pass

    def checkmain(self):
        thread = []
        if len(zhanghaolist) < 99:
            for i, file_name in enumerate(zhanghaolist, start=1):
                logging.info(f"启动线程{i}.，绑定账号为“{file_name}”")
                new_folder_path = os.path.join('output_logs', file_name)
                if not os.path.exists(new_folder_path):  # 如果file_name文件夹不存在，创建它
                    os.makedirs(new_folder_path)
                k = threading.Thread(target=checkcookieplay, args=(i,))
                thread.append(k)
            for j in thread:
                j.daemon = True
                j.start()
            time.sleep(60)
            for t in thread:
                t.join()
        else:
            logging.error(f"'账号数量超过限制，请修改后再试' ")

        pass

    def main(self):
        thread = []
        if len(zhanghaolist) < 10:
            for i, file_name in enumerate(zhanghaolist, start=1):
                logging.info(f"启动线程{i}.，绑定账号为“{file_name}”")
                new_folder_path = os.path.join('output_logs', file_name)
                if not os.path.exists(new_folder_path):  # 如果file_name文件夹不存在，创建它
                    os.makedirs(new_folder_path)
                k = threading.Thread(target=runplay, args=(i,))
                thread.append(k)
            for j in thread:
                j.daemon = True
                j.start()
            time.sleep(60)
            for t in thread:
                t.join()
        else:
            logging.error(f"'账号数量超过限制，请修改后再试' ")

    def check_login_status(self):
        while True:
            time.sleep(600)  # 10分钟

    def close_application(self):  # 定义一个插槽
        self.close()

def get_cg6_style_category(folder_path):
    folder_path = folder_path + r'\00'
    pattern_category = r"^CG6\.所属分类=(.*?),(.*?)\.txt$"

    for filename in os.listdir(folder_path):
        if re.match(pattern_category, filename):
            match = re.match(pattern_category, filename)
            category1 = match.group(1)
            category2 = match.group(2)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {category1}")
            print(f"提取的第二个字符串是: {category2}")
        else:
            continue
    return category1, category2
def get_cg_model_net_style_category(folder_path):
    folder_path = folder_path + r'\00'
    pattern_category = r"^CG模型网\.分类=(.*?),(.*?)\.txt$"

    for filename in os.listdir(folder_path):
        if re.match(pattern_category, filename):
            match = re.match(pattern_category, filename)
            category1 = match.group(1)
            category2 = match.group(2)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {category1}")
            print(f"提取的第二个字符串是: {category2}")
        else:
            continue
    return category1, category2

def get_3dliuliu_model_net_style_category(folder_path):
    folder_path = folder_path + r'\00'
    pattern_category = r"^3D溜溜\.分类=(.*?),(.*?),(.*?)\.txt$"

    for filename in os.listdir(folder_path):
        if re.match(pattern_category, filename):
            match = re.match(pattern_category, filename)
            category1 = match.group(1)
            category2 = match.group(2)
            category3 = match.group(3)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {category1}")
            print(f"提取的第二个字符串是: {category2}")
            print(f"提取的第二个字符串是: {category3}")
        else:
            continue
    return category1, category2, category3

def get_zhimo_style_category(folder_path):
    folder_path = folder_path + r'\00'
    pattern_category = r"^知末\.3D\.分类=(.*?),(.*?),(.*?)\.txt$"

    for filename in os.listdir(folder_path):
        if re.match(pattern_category, filename):
            match = re.match(pattern_category, filename)
            category1 = match.group(1)
            category2 = match.group(2)
            category3 = match.group(3)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {category1}")
            print(f"提取的第二个字符串是: {category2}")
            print(f"提取的第二个字符串是: {category3}")
        else:
            continue
    return category1, category2, category3


def get_d5a_style_category(folder_path):
    folder_path = folder_path + r'\00'
    pattern_category = r"^建E\.D5\.模型分类=(.*?),(.*?)\.txt$"
    pattern_style = r"^建E\.D5\.模型风格=(.*?)\.txt$"

    for filename in os.listdir(folder_path):
        if re.match(pattern_category, filename):
            match = re.match(pattern_category, filename)
            category1 = match.group(1)
            category2 = match.group(2)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {category1}")
            print(f"提取的第二个字符串是: {category2}")
        else:
            continue
    for filename in os.listdir(folder_path):
        if re.match(pattern_style, filename):
            match = re.match(pattern_style, filename)
            style_model = match.group(1)
            print(f"文件名：{filename}")
            print(f"提取的第一个字符串是: {style_model}")

    if category1 == '沙发':
        category1 = "4935"
        if category2 == "沙发茶几组合":
            category2 = "4953"
        elif category2 == "多人沙发":
            category2 = "4952"
        elif category2 == "双人沙发":
            category2 = "4951"
        elif category2 == "户外沙发":
            category2 = "4958"
        elif category2 == "单人沙发":
            category2 = "4950"
        elif category2 == "异形沙发":
            category2 = "4956"
        elif category2 == "懒人沙发":
            category2 = "4957"
        elif category2 == "贵妃椅":
            category2 = "4954"
        elif category2 == "卡座":
            category2 = "4959"
        elif category2 == "其他":
            category2 = "4955"
    elif category1 == '椅凳':
        category1 = "4936"
        if category2 == "单椅":
            category2 = "4965"
        elif category2 == "休闲椅":
            category2 = "4976"
        elif category2 == "办公椅":
            category2 = "4966"
        elif category2 == "吧椅":
            category2 = "4967"
        elif category2 == "躺椅":
            category2 = "4968"
        elif category2 == "儿童椅":
            category2 = "4972"
        elif category2 == "户外椅":
            category2 = "4969"
        elif category2 == "吊椅":
            category2 = "4973"
        elif category2 == "公共椅":
            category2 = "4975"
        elif category2 == "摇椅":
            category2 = "4977"
        elif category2 == "按摩椅":
            category2 = "4974"
        elif category2 == "凳子":
            category2 = "4970"
        elif category2 == "吧凳":
            category2 = "4978"
        elif category2 == "沙发凳_床尾凳":
            category2 = "4979"
        elif category2 == "其他":
            category2 = "4971"
    elif category1 == '灯具':
        category1 = "4940"
        if category2 == "吊灯":
            category2 = "5041"
        elif category2 == "壁灯":
            category2 = "5048"
        elif category2 == "水晶灯":
            category2 = "5042"
        elif category2 == "台灯":
            category2 = "5043"
        elif category2 == "落地灯":
            category2 = "5044"
        elif category2 == "吸顶灯":
            category2 = "5045"
        elif category2 == "筒灯_射灯":
            category2 = "5046"
        elif category2 == "户外灯":
            category2 = "5049"
        elif category2 == "格栅灯":
            category2 = "5050"
        elif category2 == "装饰灯":
            category2 = "5051"
        elif category2 == "其他":
            category2 = "5047"
    elif category1 == '床具':
        category1 = "4939"
        if category2 == "双人床":
            category2 = "5027"
        elif category2 == "单人床":
            category2 = "5026"
        elif category2 == "床头柜":
            category2 = "5028"
        elif category2 == "按摩床":
            category2 = "5032"
        elif category2 == "儿童床":
            category2 = "5030"
        elif category2 == "圆床":
            category2 = "5031"
        elif category2 == "高低床":
            category2 = "5033"
        elif category2 == "其他":
            category2 = "5029"
    elif category1 == '桌几':
        category1 = "4937"
        if category2 == "餐桌":
            category2 = "4980"
        elif category2 == "书桌":
            category2 = "4983"
        elif category2 == "茶桌":
            category2 = "4994"
        elif category2 == "娱乐桌":
            category2 = "4993"
        elif category2 == "茶几":
            category2 = "4981"
        elif category2 == "边几":
            category2 = "4982"
        elif category2 == "端景台":
            category2 = "4990"
        elif category2 == "梳妆台":
            category2 = "4984"
        elif category2 == "吧台":
            category2 = "4985"
        elif category2 == "接待台":
            category2 = "4992"
        elif category2 == "餐桌椅":
            category2 = "4987"
        elif category2 == "茶桌椅":
            category2 = "4988"
        elif category2 == "书桌椅":
            category2 = "4989"
        elif category2 == "办公桌椅":
            category2 = "4991"
        elif category2 == "休闲桌椅":
            category2 = "4995"
        elif category2 == "其他":
            category2 = "4986"
    elif category1 == '柜_架子':
        category1 = "4938"
        if category2 == "边柜_玄关柜":
            category2 = "5012"
        elif category2 == "电视柜":
            category2 = "5011"
        elif category2 == "书柜":
            category2 = "5014"
        elif category2 == "衣柜":
            category2 = "5013"
        elif category2 == "酒柜":
            category2 = "5015"
        elif category2 == "鞋柜":
            category2 = "5019"
        elif category2 == "装饰柜":
            category2 = "5023"
        elif category2 == "储物柜":
            category2 = "5017"
        elif category2 == "吊柜_壁柜":
            category2 = "5020"
        elif category2 == "装饰架_书架":
            category2 = "5018"
        elif category2 == "展柜_货架":
            category2 = "5021"
        elif category2 == "博古架":
            category2 = "5022"
        elif category2 == "其他":
            category2 = "5016"
    elif category1 == '陈设饰品':
        category1 = "4941"
        if category2 == "饰品摆件":
            category2 = "5057"
        elif category2 == "墙饰":
            category2 = "5059"
        elif category2 == "雕塑":
            category2 = "5066"
        elif category2 == "艺术装置":
            category2 = "5072"
        elif category2 == "窗帘布艺":
            category2 = "5056"
        elif category2 == "挂画相框":
            category2 = "5058"
        elif category2 == "地毯_挂毯":
            category2 = "5074"
        elif category2 == "抱枕":
            category2 = "5075"
        elif category2 == "服饰鞋帽":
            category2 = "5067"
        elif category2 == "装饰镜":
            category2 = "5060"
        elif category2 == "茶具":
            category2 = "5061"
        elif category2 == "钟表":
            category2 = "5062"
        elif category2 == "玩具":
            category2 = "5063"
        elif category2 == "美陈":
            category2 = "5073"
        elif category2 == "办公用品":
            category2 = "5065"
        elif category2 == "陶瓷器皿":
            category2 = "5068"
        elif category2 == "鱼缸水族":
            category2 = "5069"
        elif category2 == "旗帜徼章":
            category2 = "5070"
        elif category2 == "背景墙":
            category2 = "5071"
        elif category2 == "其他":
            category2 = "5064"
    elif category1 == '厨卫用品':
        category1 = "4942"
        if category2 == "厨房用品":
            category2 = "5087"
        elif category2 == "台盆":
            category2 = "5090"
        elif category2 == "橱柜":
            category2 = "5088"
        elif category2 == "餐具_厨具":
            category2 = "5089"
        elif category2 == "酒水食品":
            category2 = "5091"
        elif category2 == "浴缸":
            category2 = "5092"
        elif category2 == "卫浴柜":
            category2 = "5094"
        elif category2 == "坐便器_小便斗":
            category2 = "5095"
        elif category2 == "洗护用品":
            category2 = "5096"
        elif category2 == "卫浴小件":
            category2 = "5093"
        elif category2 == "基它":
            category2 = "5097"
    elif category1 == '构件五金':
        category1 = "4943"
        if category2 == "五金":
            category2 = "5110"
        elif category2 == "隔断_屏风":
            category2 = "5107"
        elif category2 == "门":
            category2 = "5105"
        elif category2 == "窗":
            category2 = "5106"
        elif category2 == "楼梯":
            category2 = "5102"
        elif category2 == "柱子":
            category2 = "5104"
        elif category2 == "栏杆":
            category2 = "5103"
        elif category2 == "雕花":
            category2 = "5108"
        elif category2 == "壁炉":
            category2 = "5109"
        elif category2 == "构件线条":
            category2 = "5111"
        elif category2 == "吊顶":
            category2 = "5112"
        elif category2 == "其他":
            category2 = "5113"
    elif category1 == '器材设备':
        category1 = "4944"
        if category2 == "家用电器":
            category2 = "5117"
        elif category2 == "数码产品":
            category2 = "5123"
        elif category2 == "运动器材":
            category2 = "5122"
        elif category2 == "交通工具":
            category2 = "5124"
        elif category2 == "医疗器材":
            category2 = "5119"
        elif category2 == "消防设施":
            category2 = "5121"
        elif category2 == "游乐设施":
            category2 = "5125"
        elif category2 == "公共设施":
            category2 = "5120"
        elif category2 == "音乐器材":
            category2 = "5126"
        elif category2 == "军事设备":
            category2 = "5127"
        elif category2 == "工业设备":
            category2 = "5128"
        elif category2 == "其他":
            category2 = "5118"
    elif category1 == '植物花草':
        category1 = "4945"
        if category2 == "盆栽盆景":
            category2 = "5132"
        elif category2 == "树木":
            category2 = "5133"
        elif category2 == "植物墙":
            category2 = "5134"
        elif category2 == "花艺_花卉":
            category2 = "5135"
        elif category2 == "植被":
            category2 = "5137"
        elif category2 == "植物景观":
            category2 = "5138"
        elif category2 == "其他":
            category2 = "5136"
    elif category1 == '动物_人物':
        category1 = "4946"
        if category2 == "人物":
            category2 = "5139"
        elif category2 == "动物":
            category2 = "5140"
        elif category2 == "虚拟人物":
            category2 = "5142"
        elif category2 == "其他":
            category2 = "5141"
    elif category1 == '建筑户外':
        category1 = "5304"
        if category2 == "户外构建":
            category2 = "5305"
    if style_model == '现代':
        style_model = '316'
    elif style_model == '中式':
        style_model = '318'
    elif style_model == '新中式':
        style_model = '319'
    elif style_model == '简欧':
        style_model = '317'
    elif style_model == '北欧':
        style_model = '320'
    elif style_model == '新古典':
        style_model = '498'
    elif style_model == '美式':
        style_model = '321'
    elif style_model == '后现代':
        style_model = '511'
    elif style_model == '工业风':
        style_model = '323'
    elif style_model == '欧式古典':
        style_model = '325'
    elif style_model == '东南亚':
        style_model = '499'
    elif style_model == '法式':
        style_model = '500'
    elif style_model == '地中海':
        style_model = '322'
    elif style_model == '日式':
        style_model = '324'
    elif style_model == '侘寂风':
        style_model = '4094'
    elif style_model == '其他':
        style_model = '326'
    return category1, category2, style_model


# 检查指定的图片文件是否存在
def check_image_exists(folder_path, base_filename, extensions):
    found_files = []
    for ext in extensions:
        full_path = os.path.join(folder_path, base_filename + ext)
        if os.path.exists(full_path):
            print(f"文件存在: {base_filename + ext}")
            found_files.append(base_filename + ext)
        else:
            print(f"文件不存在: {base_filename + ext}")
    return found_files


def match_files_300(directory):
    pattern = re.compile(r'\[300\]-(\d+)-(\d+)-.(jpg|png)')  # 匹配文件名的正则表达式

    matched_files = []

    for filename in os.listdir(directory):
        if pattern.match(filename):  # 如果文件名匹配正则表达式
            match = pattern.match(filename)
            face_count = match.group(1)  # 面数
            point_count = match.group(2)  # 点数
            extension = match.group(3)  # 文件扩展名
            matched_files.append({
                'filename': filename,
                'face_count': face_count,
                'point_count': point_count,
                'extension': extension
            })

    return matched_files

def match_files_000(directory):
    pattern = re.compile(r'\[000\]-(\d+)-(\d+)-\.(jpg|png)')  # 匹配文件名的正则表达式

    matched_files = []

    for filename in os.listdir(directory):
        if pattern.match(filename):  # 如果文件名匹配正则表达式
            match = pattern.match(filename)
            face_count = match.group(1)  # 面数
            point_count = match.group(2)  # 点数
            extension = match.group(3)  # 文件扩展名
            matched_files.append({
                'filename': filename,
                'face_count': face_count,
                'point_count': point_count,
                'extension': extension
            })

    return matched_files

def run_A01A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                #####01A01#240713194422************* 期待触发文件选择器的动作
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    # 点击触发文件选择器的按钮，该按钮位于嵌套的iframe中
                    page.frame_locator("#userIframe_0").frame_locator("#iframe1").locator("label").click()
                file_chooser = fc_info.value  # 获取文件选择器的实例
                img_name_part_name = f'[[DT]]{numeric_part}.png'  # 构造图片文件的名称，格式为[[DT]]加上数字部分，再加上.png后缀
                img_file_path = f'{target_dir}/{img_name_part_name}'  # 完整的文件路径

                # 检查文件是否存在
                if os.path.exists(img_file_path):
                    file_to_upload = img_file_path  # 如果文件存在，使用这个文件进行上传
                else:
                    file_to_upload = f'{target_dir}/[001].png'  # 如果文件不存在，使用默认的[001].png文件进行上传

                file_chooser.set_files(file_to_upload)  # 设置文件选择器要上传的文件
                page.wait_for_timeout(1000)  # 等待1000毫秒
                time.sleep(1 + random_number)  # 额外等待1秒加一个随机时间，增加健壮性
                logging.info(f"账号 '{name}成功上传 '{os.path.basename(file_to_upload)}'")  # 记录上传的文件名称
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe2").locator("label").click()
                file_chooser = fc_info.value
                img_300_name = match_files_300(target_dir)[0]['filename']
                file_chooser.set_files(f'{target_dir}/{img_300_name}')
                page.wait_for_timeout(1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传 '{img_300_name}'")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe3").locator("label").click()
                file_chooser = fc_info.value
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                file_chooser.set_files(f'{target_dir}/{img_311_name}')
                page.wait_for_timeout(1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传{img_311_name}")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe4").locator("label").click()
                file_chooser = fc_info.value
                img_311_name = f'[111].png'
                file_chooser.set_files(f'{target_dir}/{img_311_name}')
                page.wait_for_timeout(1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传{img_311_name}")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe5").locator("label").click()
                file_chooser = fc_info.value
                img_311_name = f'[211].png'
                file_chooser.set_files(f'{target_dir}/{img_311_name}')
                page.wait_for_timeout(1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传{img_311_name}")

                # Attempt to find and print the first "_V.max.rar" file in the directory
                max_file = None  # Variable to hold the name of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found, save its name and break the loop
                        if file.endswith("_V.max.rar"):
                            max_file = file
                            break  # Stop after the first match
                if max_file:
                    print(max_file)
                else:
                    print("No _V.max.rar file found in the specified directory.")
                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No _V.max.rar file found in the specified directory.")
                rtf_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if rtf_name:
                    print(rtf_name)
                else:
                    print("No rtf file found in the specified directory.")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").locator("input[name=\"modelfile\\[0\\]\"]").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f'{target_dir}/{max_file}')
                page.wait_for_timeout(1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传 '{max_file}'")
                try:
                    button = page.frame_locator("#userIframe_0").get_by_text("上传成功！重传")
                    button.click(timeout=600000)
                    logging.info(f"上传成功")
                except:
                    logging.info(f"上传失败")

                page.frame_locator("#userIframe_0").locator("select[name=\"version\\[0\\]\"]").select_option("MAX 2018")
                page.frame_locator("#userIframe_0").get_by_placeholder("请输入模型名称，例：风格+场景/单体").click()
                page.frame_locator("#userIframe_0").get_by_placeholder("请输入模型名称，例：风格+场景/单体").fill(
                    f"{txt_name}")
                page.frame_locator("#userIframe_0").get_by_placeholder(
                    "多个标签之间用空格隔开，准确填写标签，可提高曝光率哦").click()
                page.frame_locator("#userIframe_0").get_by_placeholder(
                    "多个标签之间用空格隔开，准确填写标签，可提高曝光率哦").fill(f"{rtf_name}")
                page.frame_locator("#userIframe_0").locator("#modelform div").filter(
                    has_text="我已经阅读并同意建E网《建E网用户上传合作协议》和 《素材上传说明》").locator(
                    "span").first.click()
                page.frame_locator("#userIframe_0").get_by_role("button", name="上传").click()
                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(timegap)
                page.get_by_role("link", name="首页").nth(1).click()
                page.goto(url)
        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A01B(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"
                category1, category2, style = get_d5a_style_category(target_dir)

                #####01A01#240713194422************* 期待触发文件选择器的动作
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    # 点击触发文件选择器的按钮，该按钮位于嵌套的iframe中
                    page.frame_locator("#userIframe_0").frame_locator("#iframe1").locator("label").click()
                file_chooser = fc_info.value  # 获取文件选择器的实例
                img_name_part_name = f'[[DT]]{numeric_part}.png'  # 构造图片文件的名称，格式为[[DT]]加上数字部分，再加上.png后缀
                img_file_path = f'{target_dir}/{img_name_part_name}'  # 完整的文件路径

                # 检查文件是否存在
                if os.path.exists(img_file_path):
                    file_to_upload = img_file_path  # 如果文件存在，使用这个文件进行上传
                else:
                    file_to_upload = f'{target_dir}/[001].png'  # 如果文件不存在，使用默认的[001].png文件进行上传

                file_chooser.set_files(file_to_upload)  # 设置文件选择器要上传的文件
                page.wait_for_timeout(1000)  # 等待1000毫秒
                time.sleep(1 + random_number)  # 额外等待1秒加一个随机时间，增加健壮性
                logging.info(f"账号 '{name}成功上传 '{os.path.basename(file_to_upload)}'")  # 记录上传的文件名称


                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe2").locator("label").click()
                file_chooser = fc_info.value
                existing_files = check_image_exists(target_dir, '[001]', extensions)
                img_001_name = ', '.join(existing_files)
                file_chooser.set_files(f'{target_dir}/{img_001_name}')
                page.wait_for_timeout(1000)
                logging.info(f"账号 '{name}成功上传 '{img_001_name}'")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe3").locator("label").click()
                file_chooser = fc_info.value
                existing_files = check_image_exists(target_dir, '[002]', extensions)
                img_002_name = ', '.join(existing_files)
                file_chooser.set_files(f'{target_dir}/{img_002_name}')
                page.wait_for_timeout(1000)
                logging.info(f"账号 '{name}成功上传 '{img_002_name}'")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe4").locator("label").click()
                file_chooser = fc_info.value
                existing_files = check_image_exists(target_dir, '[003]', extensions)
                img_003_name = ', '.join(existing_files)
                file_chooser.set_files(f'{target_dir}/{img_003_name}')
                page.wait_for_timeout(1000)
                logging.info(f"账号 '{name}成功上传 '{img_003_name}")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").frame_locator("#iframe5").locator("label").click()
                file_chooser = fc_info.value
                existing_files = check_image_exists(target_dir, '[004]', extensions)
                img_004_name = ', '.join(existing_files)
                file_chooser.set_files(f'{target_dir}/{img_004_name}')
                page.wait_for_timeout(1000)
                logging.info(f"账号 '{name}成功上传 '{img_004_name}")
                # Attempt to find and print the first "_V.max.rar" file in the directory
                d5a_file = None  # Variable to hold the name of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found, save its name and break the loop
                        if file.endswith(".d5a.rar"):
                            d5a_file = file
                            break  # Stop after the first match
                if d5a_file:
                    print(d5a_file)
                else:
                    print("No .d5a.rar file found in the specified directory.")

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No .txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if rtf_name:
                    print(rtf_name)
                else:
                    print("No .rtf file found in the specified directory.")

                #####上传d5a文件压缩包#240714110009**识别出现"上传完成100%"后下一步*****************************
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.frame_locator("#userIframe_0").locator("#file").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f'{target_dir}/{d5a_file}')  # 设置文件选择器的文件为之前找到的文件'.d5a.rar'压缩包
                page.wait_for_timeout(timegap * 1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传 '{d5a_file}'")
                try:
                    button = page.frame_locator("#userIframe_0").get_by_text("上传完成100%")
                    button.click(timeout=600000)    ##超时设定为600秒(10分钟).
                    logging.info(f"上传成功")
                except:
                    logging.info(f"上传失败")



                page.frame_locator("#userIframe_0").get_by_placeholder("请输入模型名称，例：风格+分类").click()
                page.frame_locator("#userIframe_0").get_by_placeholder("请输入模型名称，例：风格+分类").fill(txt_name)
                page.frame_locator("#userIframe_0").locator("#bid").select_option(category1)
                page.wait_for_timeout(timegap * 1000)
                time.sleep(random_number)
                page.frame_locator("#userIframe_0").locator("#sid").select_option(category2)
                page.wait_for_timeout(timegap * 1000)
                time.sleep(random_number)
                page.frame_locator("#userIframe_0").locator("#style").select_option(style)

                page.frame_locator("#userIframe_0").get_by_placeholder(
                    "多个标签之间用空格隔开，准确填写标签，可提高曝光率哦").click()
                page.frame_locator("#userIframe_0").get_by_placeholder(
                    "多个标签之间用空格隔开，准确填写标签，可提高曝光率哦").fill(f"{rtf_name}")
                page.frame_locator("#userIframe_0").locator("label span").first.click()
                page.frame_locator("#userIframe_0").get_by_role("button", name="上传").click()
                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(timegap)
                page.get_by_role("link", name="首页").nth(1).click()
                page.goto(url)
        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A02A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("div").filter(has_text=re.compile(
                        r"^上传压缩包付费模型\(同时作为会员模型\)30天后转会员模型\(30天后同时作为会员模型\)付费模型\(不作为会员模型\)共享模型\(免费下载\)$")).get_by_role(
                        "img").first.click()
                file_chooser = fc_info.value
                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                file_chooser.set_files(
                    [f'{target_dir}/{img_name_part_name}', f'{target_dir}/{img_311_name}', f'{target_dir}/[001].png',
                     f'{target_dir}/[002].png', f'{target_dir}/[003].png', f'{target_dir}/[004].png'])
                page.wait_for_timeout(timegap * 1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传图片")

                ####修改"_V.max.rar"为 "_Vmax.rar" 便于炫云识别***#240715120404***************[
                for filename in os.listdir(target_dir):
                    # 检查文件名是否以特定格式结尾
                    if filename.endswith("_V.max.rar"):
                        # 创建新的文件名替换结尾
                        new_filename = filename.replace("_V.max.rar", "_Vmax.rar")
                        # 完整的旧文件路径
                        old_file = os.path.join(target_dir, filename)
                        # 完整的新文件路径
                        new_file = os.path.join(target_dir, new_filename)
                        # 重命名文件
                        os.rename(old_file, new_file)
                        print(f"Renamed '{filename}' to '{new_filename}'")

                print("All relevant files have been renamed.")
                ####修改"_V.max.rar"为 "_Vmax.rar" 便于炫云识别***#240715120404***************]


                # Attempt to find and print the first "_V.max.rar" file in the directory
                max_file = None  # Variable to hold the name of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found, save its name and break the loop
                        if file.endswith("_Vmax.rar"):
                            max_file = file
                            break  # Stop after the first match
                if max_file:
                    print(max_file)
                else:
                    print("No _V.max.rar file found in the specified directory.")
                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No _V.max.rar file found in the specified directory.")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("上传压缩包").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f'{target_dir}/{max_file}')
                page.wait_for_timeout(timegap * 1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传 '{max_file}'")


                page.locator(".el-select__caret").first.click()
                page.locator("li").filter(has_text="2018").click()
                page.get_by_placeholder("请选择").nth(1).click()
                page.locator("li").filter(has_text="VR无灯光").click()

                page.get_by_placeholder("逗号隔开(例：桌子，椅子)").click()
                page.get_by_placeholder("逗号隔开(例：桌子，椅子)").fill(txt_name)
                page.get_by_role("button", name="上传").click()

                ###page.wait_for_selector("text='上传完成'", timeout=60000)  ## 增加适当的超时时间


                ####重新改回来, 修改"_Vmax.rar"为 "_V.max.rar" 便于其他网站正常使用***#240715120857***************[
                for filename in os.listdir(target_dir):
                    # 检查文件名是否以特定格式结尾
                    if filename.endswith("_Vmax.rar"):
                        # 创建新的文件名替换结尾
                        new_filename = filename.replace("_Vmax.rar", "_V.max.rar")
                        # 完整的旧文件路径
                        old_file = os.path.join(target_dir, filename)
                        # 完整的新文件路径
                        new_file = os.path.join(target_dir, new_filename)
                        # 重命名文件
                        os.rename(old_file, new_file)
                        print(f"Renamed '{filename}' to '{new_filename}'")

                print("All relevant files have been renamed.")
                ####重新改回来, 修改"_Vmax.rar"为 "_V.max.rar" 便于其他网站正常使用***#240715120857***************]

                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(3 + timegap)
                page.goto("https://www.baidu.com/")
                page.goto(url)
        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A02B(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    page.get_by_role("tab", name="SU模型").click()
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("div").filter(has_text=re.compile(
                        r"^上传压缩包付费模型\(同时作为会员模型\)30天后转会员模型\(30天后同时作为会员模型\)付费模型\(不作为会员模型\)共享模型\(免费下载\)$")).get_by_role(
                        "img").first.click()
                file_chooser = fc_info.value
                img_name_part_name = f'[[DT]]{numeric_part}.png'
                file_chooser.set_files(
                    [f'{target_dir}/{img_name_part_name}', f'{target_dir}/[111].png', f'{target_dir}/[001].png',
                     f'{target_dir}/[002].png', f'{target_dir}/[003].png', f'{target_dir}/[004].png'])
                page.wait_for_timeout(timegap * 1000)
                time.sleep(1 + random_number)
                logging.info(f"账号 '{name}成功上传图片")

                # Attempt to find and print the first "_V.max.rar" file in the directory
                skp_file = None  # Variable to hold the name of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found, save its name and break the loop
                        if file.endswith(".skp.rar"):
                            skp_file = file
                            break  # Stop after the first match
                if skp_file:
                    print(skp_file)
                else:
                    print("No _V.max.rar file found in the specified directory.")
                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No _V.max.rar file found in the specified directory.")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("上传压缩包").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f'{target_dir}/{skp_file}')
                page.wait_for_timeout(timegap * 1000)
                time.sleep(timegap + random_number)
                logging.info(f"账号 '{name}成功上传 '{skp_file}'")

                page.get_by_placeholder("请选择").first.click()
                page.locator("li").filter(has_text="2014").click()
                page.get_by_placeholder("请选择").nth(1).click()
                page.locator("li").filter(has_text="无").click()

                page.get_by_placeholder("逗号隔开(例：桌子，椅子)").click()
                page.get_by_placeholder("逗号隔开(例：桌子，椅子)").fill(txt_name)
                page.get_by_role("button", name="上传").click()

                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(timegap)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)
                page.get_by_role("tab", name="SU模型").click()
        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A03A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")

                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                max_namne = f"{numeric_part}_V.max.rar"
                blend_name = f"{numeric_part}.blend.rar"
                fbx_name = f"{numeric_part}.fbx.rar"
                glb_name = f"{numeric_part}.glb.rar"
                skp_name = f"{numeric_part}.skp.rar"

                page.get_by_placeholder("请输入标题，标题不超过50个字").click()
                page.get_by_placeholder("请输入标题，标题不超过50个字").fill(txt_name)
                for tag in tag_list:
                    page.get_by_placeholder("请输入标签").click()
                    page.get_by_placeholder("请输入标签").fill(tag)
                    page.get_by_role("button", name="添加").click()

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("#empty_img").get_by_role("textbox").click()
                file_chooser = fc_info.value  # 获取文件选择器的实例

                img_file_path = f'{target_dir}/{img_name_part_name}'  # 完整的文件路径

                # 检查文件是否存在
                if os.path.exists(img_file_path):
                    file_to_upload = img_file_path  # 如果文件存在，使用这个文件进行上传
                else:
                    file_to_upload = f'{target_dir}/[001].png'  # 如果文件不存在，使用默认的[001].png文件进行上传

                file_chooser.set_files(file_to_upload)  # 设置文件选择器要上传的文件
                page.get_by_role("button", name="提交").click()
                page.wait_for_timeout(timegap * 1000)




                rar_name = f"{numeric_part}_V.max.rar"
                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[4]/div[2]/div").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f"{target_dir}/{numeric_part}_V.max.rar")
                page.wait_for_timeout(timegap * 1000)

                # page.get_by_placeholder("请选择文件格式").click()
                page.get_by_placeholder("请选择文件格式").click(timeout=600000)   ##超时设置为600秒

                page.get_by_placeholder("请选择文件格式").fill(".max")
                page.get_by_placeholder("请输入版本").click()
                page.get_by_placeholder("请输入版本").fill("2018")
                page.get_by_placeholder("请选择渲染器").click()
                page.get_by_placeholder("请选择渲染器").fill("VRay")
                page.get_by_placeholder("请选择渲染器").press("Enter")
                page.get_by_placeholder("请选择渲染器").click()
                page.get_by_placeholder("请选择渲染器").fill("VRay")
                page.get_by_text("VRay", exact=True).click()
                page.get_by_placeholder("请输入版本").nth(1).click()
                page.get_by_placeholder("请输入版本").nth(1).fill("6")

                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[4]/div[2]/div").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f"{target_dir}/{numeric_part}.blend.rar")
                page.wait_for_timeout(timegap * 1000)

                page.locator("li").filter(
                    has_text=f"{numeric_part}.blend.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dw").get_by_placeholder(
                    "请选择文件格式").click(timeout=600000)    ##超时设置为600秒
                page.locator("li").filter(
                    has_text=f"{numeric_part}.blend.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dw").get_by_placeholder(
                    "请选择文件格式").fill(".blend")
                page.locator("li").filter(
                    has_text=f"{numeric_part}.blend.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dw").get_by_placeholder(
                    "请输入版本").click()
                page.get_by_placeholder("请输入版本").nth(2).fill("3.6")
                page.locator("li").filter(
                    has_text=f"{numeric_part}.blend.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dw").get_by_placeholder(
                    "请选择渲染器").click()
                page.get_by_text("默认", exact=True).click()

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[4]/div[2]/div").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f"{target_dir}/{numeric_part}.fbx.rar")
                page.wait_for_timeout(timegap * 1000)
                page.locator("li").filter(
                    has_text=f"{numeric_part}.fbx.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").click(timeout=600000)    ##超时设置为600秒
                page.locator("li").filter(
                    has_text=f"{numeric_part}.fbx.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").fill(".fbx")
                page.locator("li").filter(
                    has_text=f"{numeric_part}.fbx.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").click()
                page.locator("li").filter(
                    has_text=f"{numeric_part}.fbx.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").fill("2020")
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[4]/div[2]/div").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f"{target_dir}/{numeric_part}.glb.rar")
                page.wait_for_timeout(timegap * 1000)

                page.locator("li").filter(
                    has_text=f"{numeric_part}.glb.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").click(timeout=600000)    ##超时设置为600秒
                page.locator("li").filter(
                    has_text=f"{numeric_part}.glb.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").fill(".glb")
                page.locator("li").filter(
                    has_text=f"{numeric_part}.glb.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").click()
                page.locator("li").filter(
                    has_text=f"{numeric_part}.glb.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").fill("2.0")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[4]/div[2]/div").click()
                file_chooser = fc_info.value
                file_chooser.set_files(f"{target_dir}/{numeric_part}.skp.rar")
                page.wait_for_timeout(timegap * 1000)

                page.locator("li").filter(
                    has_text=f"{numeric_part}.skp.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").click(timeout=600000)    ##超时设置为600秒
                page.locator("li").filter(
                    has_text=f"{numeric_part}.skp.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请选择文件格式").fill(".skp")
                page.locator("li").filter(
                    has_text=f"{numeric_part}.skp.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").click()
                page.locator("li").filter(
                    has_text=f"{numeric_part}.skp.rar 100% .max.ma/mb.obj.3ds.fbx.c4d.ztl.UE4.unitypackage.3dm.blend.dwg.").get_by_placeholder(
                    "请输入版本").fill("2014")

                upload_div_pre = page.locator("//*[@id='create-form']/form/div[6]/div[2]/div/div")
                # 使用鼠标移动到该区域以显示按钮
                upload_div_pre.hover()
                # 等待一段时间确保按钮已显示
                page.wait_for_timeout(1000)  # 例如等待 1 秒钟
                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[6]/div[2]/div/div/div[2]/input").click()
                file_chooser = fc_info.value

                img_file_path = f'{target_dir}/{img_name_part_name}'  # 完整的文件路径

                # 检查文件是否存在
                if os.path.exists(img_file_path):
                    file_to_upload = img_file_path  # 如果文件存在，使用这个文件进行上传
                else:
                    file_to_upload = f'{target_dir}/[001].png'  # 如果文件不存在，使用默认的[001].png文件进行上传

                file_chooser.set_files(
                    [f"{file_to_upload}", f"{target_dir}/[001].png", f"{target_dir}/[002].png",
                     f"{target_dir}/[003].png", f"{target_dir}/[004].png"])
                page.wait_for_timeout(timegap * 4000)

                upload_div_face = page.locator("//*[@id='create-form']/form/div[6]/div[4]/div/div")
                # 使用鼠标移动到该区域以显示按钮
                upload_div_face.hover()
                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.locator("//*[@id='create-form']/form/div[6]/div[4]/div/div/div[2]/input").click()
                file_chooser = fc_info.value
                file_chooser.set_files(
                    [f'{target_dir}/{img_000_name}', f"{target_dir}/[111].png", f"{target_dir}/{img_300_name}",
                     f"{target_dir}/{img_311_name}"])
                page.wait_for_timeout(timegap * 1000)

                page.get_by_placeholder("请输入面数").click()
                page.get_by_placeholder("请输入面数").fill(face_count)
                page.get_by_placeholder("请输入点数").click()
                page.get_by_placeholder("请输入点数").fill(point_count)
                page.locator("#wrap-item-wireType i").click()
                page.get_by_text("四边形", exact=True).click()
                page.locator("#wrap-item-uv i").click()
                page.get_by_text("已展开，不重叠").click()
                page.locator(".upload_attachment_ul_bottom > li > div > i").first.click()
                page.locator(".upload_attachment_ul_bottom > li:nth-child(4) > div > i").click()
                # 找到内容可编辑的 div 元素
                editable_div = page.locator('.w-e-text')

                # 清空内容并输入新内容
                editable_div.fill("包含格式: blend(3.6)--fbx(2014)--glb(2.0)--max(2018)--skp(2014).材质齐全")

                page.get_by_placeholder("1元=10下载币").click()
                page.get_by_placeholder("1元=10下载币").fill("100")
                active_span = page.locator('span.active')

                if not active_span.count():
                    # 如果不存在，则执行点击操作
                    page.locator('.agree > span').first.click()
                    page.get_by_role('button', name='我已阅读并同意').click()
                page.locator(".charge_share > .icon").first.click()
                page.get_by_text("不可商用授权").click()
                page.locator("#create-form").get_by_text("发布", exact=True).click()

                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A04A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")

                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                cg6_style1, cg6_style2=get_cg6_style_category(target_dir)
                if "_" in cg6_style2:
                    cg6_style2=cg6_style2.replace('_', '/')
                if "小汽车" in cg6_style2:
                        cg6_style2 = cg6_style2.replace('小汽车', '小吃车')
                print(cg6_style2)
                time.sleep(2)
                page.locator("div").filter(has_text=re.compile(r"^请选择cg模型库cg资源库CG作品库软件下载$")).locator("i").click()
                page.locator("dd").filter(has_text="cg模型库").click()
                time.sleep(2)
                page.locator("//*[@id='add_form']/div[1]/div/div[2]/div/div").click()
                time.sleep(2)
                page.locator("dd").filter(has_text=cg6_style1).click()
                time.sleep(2)
                page.locator("div:nth-child(4) > div > .layui-select-title > .layui-edge").first.click()
                page.locator("dd").filter(has_text=cg6_style2).click()
                page.locator("html").click()
                page.get_by_placeholder("请输入作品标题").click()
                page.get_by_placeholder("请输入作品标题").fill(txt_name)
                page.locator("#credit").click()
                page.locator("#credit").fill("15")
                page.get_by_title("源代码").locator("div").click()
                page.locator("textarea").fill("包含格式: blend(3.6)--fbx(2014)-max(2018)).材质齐全")
                page.get_by_title("源代码").locator("div").click()
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("span").filter(has_text="上传图片").locator("label").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}'])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("span").filter(has_text="上传图片").locator("label").click()
                file_chooser = fc_info.value
                file_chooser.set_files(
                    [f'{target_dir}/{img_000_name}', f'{target_dir}/[001].png', f"{target_dir}/[002].png", f"{target_dir}/[003].png", f"{target_dir}/[004].png", f"{target_dir}/[111].png",
                     f'{target_dir}/{img_300_name}', f"{target_dir}/{img_311_name}"])

                page.locator("div").filter(has_text=re.compile(
                    r"^请选择5千以下5千-1万1万-3万3万-10万10万-100万100万以上$")).get_by_placeholder("请选择").click()
                if int(face_count)<5000:
                    page.locator("dd").filter(has_text="5千以下").click()
                elif int(face_count)>5000 and int(face_count)<10000:
                    page.locator("dd").filter(has_text="5千-1万").click()
                elif int(face_count)>10000 and int(face_count)<30000:
                    page.locator("dd").filter(has_text="1万-3万").click()
                elif int(face_count)>30000 and int(face_count)<100000:
                    page.locator("dd").filter(has_text="3万-10万").click()
                elif int(face_count)>100000 and int(face_count)<1000000:
                    page.locator("dd").filter(has_text="10万-100万").click()
                elif int(face_count)>1000000 :
                    page.locator("dd").filter(has_text="100万以上").click()

                page.locator("div").filter(
                    has_text=re.compile(r"^请选择三角形四边形N边形三角形\+四边形$")).get_by_placeholder(
                    "请选择").click()
                page.locator("dd").filter(has_text=re.compile(r"^四边形$")).click()
                page.locator("div").filter(has_text=re.compile(r"^3ds Max$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^Blender$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^Fbx$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^贴图$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^材质$")).locator("i").click()
                page.get_by_placeholder("请输入软件版本").click()
                page.get_by_placeholder("请输入软件版本").fill("包含格式: blend(3.6)--fbx(2014)-max(2018)).材质齐全")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_role("link", name=" 添加本地附件").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f"{target_dir}/{numeric_part}.blend.rar", f"{target_dir}/{numeric_part}.fbx.rar", f"{target_dir}/{numeric_part}_V.max.rar"])
                time.sleep(4 + timegap * 2)

                page.get_by_role("button", name="立即提交").click()


                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A05A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")

                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                cg6_style1, cg6_style2=get_cg6_style_category(target_dir)
                if "_" in cg6_style2:
                    cg6_style2=cg6_style2.replace('_', '/')
                if "小汽车" in cg6_style2:
                        cg6_style2 = cg6_style2.replace('小汽车', '小吃车')
                print(cg6_style2)
                time.sleep(2)
                page.locator("div").filter(has_text=re.compile(r"^请选择cg模型库cg资源库传奇资源软件下载教程$")).locator("i").click()

                page.locator("dd").filter(has_text="cg模型库").click()
                time.sleep(2)
                page.locator("div:nth-child(3) > div > .layui-select-title > .layui-edge").first.click()
                time.sleep(2)
                page.locator("dd").filter(has_text=cg6_style1).click()
                time.sleep(2)
                page.locator("div:nth-child(4) > div > .layui-select-title > .layui-edge").first.click()
                page.locator("dd").filter(has_text=cg6_style2).click()
                page.locator("html").click()
                page.get_by_placeholder("请输入作品标题").click()
                page.get_by_placeholder("请输入作品标题").fill(txt_name)
                page.locator("#credit").click()
                page.locator("#credit").fill("15")
                page.get_by_title("源代码").locator("div").click()
                page.locator("textarea").fill("包含格式: blend(3.6)--fbx(2014)-max(2018)).材质齐全")
                page.get_by_title("源代码").locator("div").click()
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("span").filter(has_text="上传图片").locator("label").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}'])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("span").filter(has_text="上传图片").locator("label").click()
                file_chooser = fc_info.value
                file_chooser.set_files(
                    [f'{target_dir}/{img_000_name}', f'{target_dir}/[001].png', f"{target_dir}/[002].png", f"{target_dir}/[003].png", f"{target_dir}/[004].png", f"{target_dir}/[111].png",
                     f'{target_dir}/{img_300_name}', f"{target_dir}/{img_311_name}"])

                page.locator("div").filter(has_text=re.compile(
                    r"^请选择5千以下5千-1万1万-3万3万-10万10万-100万100万以上$")).get_by_placeholder("请选择").click()
                if int(face_count)<5000:
                    page.locator("dd").filter(has_text="5千以下").click()
                elif int(face_count)>5000 and int(face_count)<10000:
                    page.locator("dd").filter(has_text="5千-1万").click()
                elif int(face_count)>10000 and int(face_count)<30000:
                    page.locator("dd").filter(has_text="1万-3万").click()
                elif int(face_count)>30000 and int(face_count)<100000:
                    page.locator("dd").filter(has_text="3万-10万").click()
                elif int(face_count)>100000 and int(face_count)<1000000:
                    page.locator("dd").filter(has_text="10万-100万").click()
                elif int(face_count)>1000000 :
                    page.locator("dd").filter(has_text="100万以上").click()

                page.locator("div").filter(
                    has_text=re.compile(r"^请选择三角形四边形N边形三角形\+四边形$")).get_by_placeholder(
                    "请选择").click()
                page.locator("dd").filter(has_text=re.compile(r"^四边形$")).click()
                page.locator("div").filter(has_text=re.compile(r"^3ds Max$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^Blender$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^Fbx$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^贴图$")).locator("i").click()
                page.locator("div").filter(has_text=re.compile(r"^材质$")).locator("i").click()
                page.get_by_placeholder("请输入软件版本").click()
                page.get_by_placeholder("请输入软件版本").fill("包含格式: blend(3.6)--fbx(2014)-max(2018)).材质齐全")

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_role("link", name=" 添加本地附件").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f"{target_dir}/{numeric_part}.blend.rar", f"{target_dir}/{numeric_part}.fbx.rar", f"{target_dir}/{numeric_part}_V.max.rar"])
                time.sleep(4 + timegap * 2)

                page.get_by_role("button", name="立即提交").click()


                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()

def run_A06A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)

    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")


                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2 = get_cg_model_net_style_category(target_dir)
                if "特效动画_" in style1 :
                    style1=style1.replace('特效动画_', '特效动画／')
                elif "飞机_" in style1:
                        style1 = style1.replace('飞机_', '飞机／')
                elif "特效动画_" in style1:
                        style1 = style1.replace('特效动画_', '特效动画／')
                elif "_" in style1:
                    style2 = style2.replace('_', '/')
                if "_" in style2:
                    style2=style2.replace('_', '/')


                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("#dropPreview label").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}'])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("#dropPreview label").click()
                file_chooser = fc_info.value
                file_chooser.set_files(
                    [ f'{target_dir}/[001].png', f"{target_dir}/[002].png", f"{target_dir}/[003].png", f"{target_dir}/[004].png"])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("#dropWire label").click()
                file_chooser = fc_info.value
                file_chooser.set_files(
                    [f'{target_dir}/{img_000_name}',  f"{target_dir}/[111].png",
                     f'{target_dir}/{img_300_name}', f"{target_dir}/{img_311_name}"])


                page.get_by_placeholder("输入个人授权价格").click()
                page.get_by_placeholder("输入个人授权价格").fill("30")
                page.get_by_text("*上传预览图").click()
                page.locator(".text-main9 > .iconfont").first.click()

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("点击上传附件").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}_V.max.rar',f'{target_dir}/{numeric_part}.blend.rar',f'{target_dir}/{numeric_part}.fbx.rar',f'{target_dir}/{numeric_part}.glb.rar',f'{target_dir}/{numeric_part}.skp.rar'])
                time.sleep(timegap)
                page.get_by_text("完成", exact=True).first.click()

                page.get_by_placeholder("请输入文件格式").first.click()
                page.get_by_role("link", name="3ds Max(.max)").click()
                page.get_by_placeholder("输入版本").first.click()
                page.get_by_placeholder("输入版本").first.fill("2018")
                page.get_by_placeholder("请输入渲染器").click()
                page.get_by_role("link", name="Vray").click()
                page.locator("input[name=\"software\"]").click()
                page.locator("input[name=\"software\"]").fill("6")


                page.get_by_text("完成", exact=True).nth(1).click()

                time.sleep(timegap)
                page.get_by_placeholder("请输入文件格式").nth(1).click()
                page.get_by_role("link", name="Blender(.blend)").click()
                page.get_by_placeholder("输入版本").nth(2).click()
                page.get_by_placeholder("输入版本").nth(2).fill("3.6")
                page.locator("div").filter(
                    has_text=re.compile(r"^默认TheaIndigoVrayCyclesEeveeClayRenderMax其他$")).get_by_placeholder(
                    "请输入渲染器").click()
                page.get_by_role("link", name="默认").click()

                page.get_by_text("完成", exact=True).nth(2).click()

                time.sleep(timegap)
                page.get_by_placeholder("请输入文件格式").nth(2).click()
                page.get_by_role("link", name="FBX(.fbx)").click()
                page.get_by_placeholder("输入版本").nth(3).click()
                page.get_by_placeholder("输入版本").nth(3).fill("2020")


                time.sleep(timegap)
                page.get_by_text("完成", exact=True).nth(3).click()
                page.get_by_placeholder("请输入文件格式").nth(3).click()
                page.get_by_role("link", name="glTF(.gltf/.glb)").click()


                time.sleep(timegap)
                page.get_by_text("完成", exact=True).nth(4).click()

                page.get_by_placeholder("请输入文件格式").nth(4).click()
                page.get_by_role("link", name="sketchup(.skp)").click()

                page.get_by_role("link", name="下一步>").click()
                page.get_by_placeholder("请输入标题，5~30个字以内，用空格隔开").click()
                page.get_by_placeholder("请输入标题，5~30个字以内，用空格隔开").fill(txt_name)
                page.locator("p").filter(has_text="请选择一级分类").click()
                page.get_by_role("link", name=style1).click()
                page.get_by_text("请选择二级分类").click()
                try:
                    button = page.get_by_role("link", name=style2)
                    button.click(timeout=1000)
                    logging.info(f"成功选择分类{style2}")
                except:
                    logging.info(f"选择分类{style2}失败")
                    if '/' in style2:
                        style2=style2.replace('/','／')
                        try:
                            button = page.get_by_role("link", name=style2)
                            button.click(timeout=1000)
                            logging.info(f"成功选择分类{style2}")
                        except:
                            logging.info(f"选择分类{style2}失败")
                            if '／' in style2:
                                style2 = style2.replace('／', '_')
                                try:
                                    button = page.get_by_role("link", name=style2)
                                    button.click(timeout=1000)
                                    logging.info(f"成功选择分类{style2}")
                                except:
                                    logging.info(f"选择分类{style2}失败，跳过选择")


                page.get_by_text("选择风格").click()
                page.get_by_role("link", name="写实").click()
                try:
                    button = page.get_by_text("选择地域")
                    button.click(timeout=1000)
                    page.get_by_role("link", name="东方").click()
                    logging.info(f"成功选择地域")

                except:
                    logging.info(f"无需选择地域")
                page.get_by_placeholder("请输入面数").click()
                page.get_by_placeholder("请输入面数").fill(face_count)
                page.get_by_placeholder("请输入点数").click()
                page.get_by_placeholder("请输入点数").fill(point_count)
                page.get_by_text("请选择布线类型").click()
                page.get_by_role("link", name="四边形", exact=True).click()
                page.get_by_text("关于UV", exact=True).click()
                page.get_by_role("link", name="已展开，不重叠").click()
                page.locator("div:nth-child(4) > i").click()
                page.locator("div:nth-child(5) > i").click()
                page.locator("#wordDes").click()
                page.locator("#wordDes").fill("包含格式:blend(3.6)--fbx(2014)-max(2018)).村质齐全")
                i=0
                for tag in tag_list:
                    if i==0:
                        page.locator("#labeldiv").click()
                        page.locator("#inputLable").fill(tag)
                        page.locator("#inputLable").press("Enter")
                    else:
                        page.locator("#inputLable").click()
                        page.locator("#inputLable").press(tag)
                        page.locator("#inputLable").press("Enter")
                        i=i+1
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("上传图片封面").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}'])
                page.locator(".jcrop-tracker").first.click()
                page.get_by_role("button", name="提交").click()
                page.get_by_role("link", name="发布", exact=True).click()
                page.get_by_role("link", name="回模型列表").click()


                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()

def run_A07A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    time.sleep(timegap)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")
                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2,style3 = get_3dliuliu_model_net_style_category(target_dir)
                try:
                    button = page.locator("#layui-layer2").get_by_role("link")
                    button.click(timeout=1000)
                    logging.info(f"关闭弹窗")
                except:
                    logging.info(f"无需关闭弹窗")
                try:
                    button = page.locator("#layui-layer1").get_by_role("link").nth(1)
                    button.click(timeout=1000)
                    logging.info(f"关闭弹窗")
                except:
                    logging.info(f"无需关闭弹窗")
                page.get_by_placeholder("请选择分类或输入关键词查询").click()
                page.locator("span").filter(has_text=style1).click()
                time.sleep(timegap)

                page.locator("span").filter(has_text=re.compile(r"^"+style2+r"$")).click()
                time.sleep(timegap)
                page.locator("span").filter(has_text=style3).first.click()
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("#zipUpload_1").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}_V.max.rar'])
                page.get_by_text("上传成功！").click()

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("div:nth-child(7) > .layui-input-block > .layui-upload-drag").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}'])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator(".images-list-ongoing > div:nth-child(2)").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_300_name}', f"{target_dir}/{img_311_name}"])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator(".images-list-ongoing > div:nth-child(4)").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/[001].png', f"{target_dir}/[002].png", f"{target_dir}/[003].png", f"{target_dir}/[004].png"])

                page.get_by_placeholder("请输入标题（示例：现代客厅 沙发组合 摆件）").click()
                page.get_by_placeholder("请输入标题（示例：现代客厅 沙发组合 摆件）").fill(txt_name)
                page.get_by_placeholder("请选择风格或输入关键词查询").click()
                page.get_by_text("现代", exact=True).click()
                page.get_by_role("button", name="提交").click()

                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A08A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    time.sleep(timegap)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")


                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2,style3 = get_3dliuliu_model_net_style_category(target_dir)

                page.get_by_placeholder("请输入模型名称\n(示例：简欧客厅,沙发组合,茶具茶几,边柜,电视柜,电视墙)").click()
                page.get_by_placeholder("请输入模型名称\n(示例：简欧客厅,沙发组合,茶具茶几,边柜,电视柜,电视墙)").fill(txt_name)
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.locator("input[type=\"file\"]").nth(1).click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}',f'{target_dir}/{img_300_name}', f"{target_dir}/{img_311_name}",f'{target_dir}/[001].png', f"{target_dir}/[002].png", f"{target_dir}/[003].png", f"{target_dir}/[004].png"])


                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_label("", exact=True).first.click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}_V.max.rar'])

                page.get_by_role("combobox").select_option("2018")
                page.get_by_placeholder("如:3.0").click()
                page.get_by_placeholder("如:3.0").fill("6")
                page.get_by_label("无").check()
                page.get_by_placeholder("请定价").click()
                page.get_by_placeholder("请定价").fill("28")
                page.locator("label").filter(has_text="我已阅读并同意").locator("span").click()
                try:
                    button = page.get_by_role("button", name="我已知悉并同意")
                    button.click(timeout=1000)

                except:
                    logging.info(f"无需同意")

                page.locator("form").get_by_text("上传", exact=True).click()
                page.get_by_text("已上传").click()


                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A08B(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    time.sleep(timegap)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")

                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2, style3 = get_3dliuliu_model_net_style_category(target_dir)
                page.locator("span").filter(has_text="SU模型").nth(1).click()
                page.get_by_placeholder("请输入模型名称").click()
                page.get_by_placeholder("请输入模型名称").fill(txt_name)
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_role("textbox").nth(2).click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}', f'{target_dir}/[111].png', f'{target_dir}/[001].png',
                                        f"{target_dir}/[002].png", f"{target_dir}/[003].png",
                                        f"{target_dir}/[004].png"])

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_label("", exact=True).click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}.skp.rar'])

                page.get_by_role("combobox").select_option("2014")
                page.get_by_placeholder("请定价").click()
                page.get_by_placeholder("请定价").fill("28")
                page.locator("label").filter(has_text="我已阅读并同意").locator("span").click()

                try:
                    button = page.get_by_role("button", name="我已知悉并同意")
                    button.click(timeout=1000)

                except:
                    logging.info(f"无需同意")
                page.locator("form").get_by_text("上传", exact=True).click()
                page.get_by_text("已上传").click()

                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()

def run_A09A(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    time.sleep(timegap)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")


                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2, style3 = get_zhimo_style_category(target_dir)

                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.get_by_role("button", name="支持多选上传图片 最多上传4张").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}',f'{target_dir}/{img_300_name}',f'{target_dir}/{img_311_name}'])
                time.sleep(timegap)

                page.locator("#upload_fileModel").get_by_role("combobox").click()
                time.sleep(timegap)
                page.locator("#upload_fileModel svg").click()

                page.get_by_role("option", name="MAX 2018").click()

                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("点击上传模型").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}_V.max.rar'])
                time.sleep(timegap)
                page.get_by_placeholder("请选择分类，或输入关键词查询分类").click()
                page.get_by_text("3D模型可上传3D模型").click()
                page.get_by_text(style1).click()
                page.get_by_text(style2, exact=True).click()
                page.get_by_text(style3).click()
                page.get_by_placeholder("请输入标题（示例：现代轻奢客餐厅 沙发茶几 装饰摆件）").click()
                page.get_by_placeholder("请输入标题（示例：现代轻奢客餐厅 沙发茶几 装饰摆件）").fill(txt_name)
                page.get_by_label("VR材质有贴图").check()
                page.get_by_label("无灯光").check()
                page.get_by_label("非独家").check()
                page.get_by_role("checkbox", name="我已阅读并同意 知末网").check()
                page.get_by_role("tabpanel").get_by_text("上传", exact=True).click()


                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def run_A09B(playwright: Playwright, num, url, name, model_path) -> None:
    global data
    global account_status  # 引用全局状态字典
    extensions = ['.jpg', '.png']
    account = name
    # 更新状态到 "运行中"
    account_status[account] = '运行中'
    timegap = data['轮询时间（单位：秒）']
    timegap = int(timegap)
    openbrowser = data['浏览器窗口是否显示（0：显示。1：关闭）']
    openbrowser = int(openbrowser)
    pythoncom.CoInitialize()
    with open(f"AccountData/AccountCookie/{name}.json") as f:
        storage_state = json.loads(f.read())
    if openbrowser == 1:
        browser = playwright.chromium.launch()
        logging.info("隐藏模式启动浏览器")
    else:
        browser = playwright.chromium.launch(headless=False)
        logging.info("模拟模式启动浏览器")
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    logging.info(f"账号 '{name}' ，加载cookie成功")
    # 打开新的页面
    page = context.new_page()
    page.goto(url, timeout=60000)
    time.sleep(timegap)
    logging.info(f"账号 '{name}' ，前往上传页面")
    results = []
    for dir_name in model_path:
        folder_name = os.path.basename(dir_name)
        split_index = next((i for i, c in enumerate(folder_name ) if not c.isdigit()), len(folder_name))
        numeric_part = folder_name[:split_index]
        name_part = folder_name [split_index:].strip("_")  # Remove leading underscores if present
        results.append((numeric_part, name_part))
        target_dir = f"{dir_name}"
        store_name = f"{name}_{numeric_part}_{name_part}"
        if not store_name in overartical:
            current_date_file_path = f'output_logs/log/{current_date}_{name}.txt'
            all_file_path = f'output_logs/all_model.txt'
            with open(all_file_path, 'r', encoding="utf-8") as f:
                existing_titles = f.read()
            if store_name not in existing_titles:
                print(f"Numeric Part: {numeric_part}")
                print(f"Name Part: {name_part}")
                print("-" * 40)  # Separator line for readability
                account_status[account] = '上传中'  # 更新状态到 "上传中"

                txt_name = None  # Variable to hold the name part of the found file
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".txt"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            txt_name = file[split_index:].strip("_").rstrip(
                                ".txt").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match
                if txt_name:
                    print(txt_name)
                else:
                    print("No txt file found in the specified directory.")

                rtf_name = None  # Variable to hold the name part of the found file
                tag_list = []
                if os.path.exists(target_dir):
                    # Iterate through files in the target directory
                    for file in os.listdir(target_dir):
                        # If a file with the "_V.max.rar" extension is found
                        if file.endswith(".rtf"):
                            # Split the file name to separate the numeric part from the name part
                            split_index = next((i for i, c in enumerate(file) if not c.isdigit()), len(file))
                            rtf_name = file[split_index:].strip("_").rstrip(
                                ".rtf").strip()  # Strip leading underscores and the file extension, then trim
                            break  # Stop after the first match

                if rtf_name:
                    print(rtf_name)
                    tag_list = rtf_name.split()
                else:
                    print("No rtf file found in the specified directory.")


                img_name_part_name = f'[[DT]]{numeric_part}.png'
                img_311_name = f'[311]{numeric_part}[!!].jpg'
                img_300_name = match_files_300(target_dir)[0]['filename']
                img_000_name = match_files_000(target_dir)[0]['filename']
                face_count = match_files_300(target_dir)[0]['face_count']
                point_count = match_files_300(target_dir)[0]['point_count']
                style1, style2, style3 = get_zhimo_style_category(target_dir)

                page.get_by_role("main").get_by_text("SU模型").click()
                with page.expect_file_chooser(timeout=6000) as fc_info:
                    page.get_by_role("button", name="请上传SU渲染图和草图 支持一次上传1-4张图片").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{img_name_part_name}',f'{target_dir}/[111].png',f'{target_dir}/[001].png',f'{target_dir}/[002].png'])
                time.sleep(timegap*4)


                page.locator("div").filter(has_text=re.compile(r"^先选择版本，再上传文件\(建议上传8\.0版本\)$")).nth(
                    2).click()
                time.sleep(timegap)


                page.get_by_role("option", name="sketchup 2014").click()
                with page.expect_file_chooser(timeout=60000) as fc_info:
                    page.get_by_text("点击上传模型").click()
                file_chooser = fc_info.value
                file_chooser.set_files([f'{target_dir}/{numeric_part}.skp.rar'])
                time.sleep(timegap)
                page.get_by_placeholder("请选择分类，或输入关键词查询分类").click()
                page.get_by_text("SU模型可上传SU模型").click()
                page.get_by_text(style1).click()
                time.sleep(timegap)
                page.get_by_text(style2, exact=True).click()
                time.sleep(timegap)
                page.get_by_text(style3).click()
                page.get_by_placeholder("请输入标题（示例：现代轻奢客餐厅 沙发茶几 装饰摆件）").click()
                page.get_by_placeholder("请输入标题（示例：现代轻奢客餐厅 沙发茶几 装饰摆件）").fill(txt_name)
                page.locator("#upload_renderer").get_by_label("无").check()
                try:
                    button = page.get_by_text("3D", exact=True)
                    button.click(timeout=1000)
                    logging.info(f"3D模型勾选")
                except:
                    logging.info(f"无需3D模型勾选")
                page.get_by_label("有").check()
                page.get_by_label("非独家").check()
                page.get_by_role("checkbox", name="我已阅读并同意 知末网").check()
                page.get_by_role("tabpanel").get_by_text("上传", exact=True).click()



                with open(current_date_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                with open(all_file_path, 'a', encoding="utf-8") as f:
                    f.write(f'{store_name}\n')
                time.sleep(4 + timegap * 2)
                page.goto("https://www.baidu.com/")
                page.goto(url, timeout=60000)

        else:
            print(f'{store_name}任务已完成')
            continue
    print('所有任务已完成')
    page.close()
    context.close()
    browser.close()


def getcookie(playwright: Playwright) -> None:
    name = data['保存指定网站cookie（输入编号)']
    name = name[0]
    url = ''
    if name == 'A01A':
        url = "https://reg.justeasy.cn/User/model/modelupload.php"

    elif name == 'A01B':
        url = "https://reg.justeasy.cn/User/d5model/modelupload.php"

    elif name == 'A01C':
        url = "https://reg.justeasy.cn/User/sumodel/modelupload.php"

    elif name == 'A01D':
        url = "https://reg.justeasy.cn/User/tietu/tietupload.php"

    elif name == 'A01E':
        url = "https://reg.justeasy.cn/User/cad/cadupload.php"

    elif name == 'A02A':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"

    elif name == 'A02B':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"

    elif name == 'A02C':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"

    elif name == 'A03A':
        url = "https://www.cg99.com/models/create/model"

    elif name == 'A04A':
        url = "https://www.cg6.com/plugin.php?id=cg6_down:t&ac=add"

    elif name == 'A05A':
        url = "https://www.cgmxw.com/plugin.php?id=cg6_down:t&ac=add"

    elif name == 'A06A':
        url = "https://www.cgmodel.com/works/model-publish-v.html"

    elif name == 'A07A':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A07B':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A07C':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A07D':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A08A':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A08B':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A08C':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A08D':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A09A':
        url = "https://www.znzmo.com/creatorCenter/upload"
    elif name == 'A09B':
        url = "https://www.znzmo.com/creatorCenter/upload"
    elif name == 'A09C':
        url = "https://www.znzmo.com/creatorCenter/upload"
    elif name == 'A09D':
        url = "https://www.znzmo.com/creatorCenter/upload"
    else:
        print("编号错误，请重新输入")
        return

    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    # Open new page
    page = context.new_page()
    js = """
            Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});
            """
    page.add_init_script(js)
    page.goto(url)
    time.sleep(60)
    storage = context.storage_state()
    with open(f"AccountData/AccountCookie/{name}.json", "w") as f:
        f.write(json.dumps(storage))
    logging.info(f"账号： '{name}.json' 已成功保存.")
    # 关闭页面
    page.close()
    context.close()
    browser.close()


def checkcookie(playwright: Playwright, num) -> None:
    with open(f"AccountData/AccountCookie/{zhanghaolist[num - 1]}.json") as f:
        storage_state = json.loads(f.read())
    browser = playwright.chromium.launch(headless=False)  # headless=False
    # 加载状态
    context = browser.new_context(storage_state=storage_state)
    # Open new page
    page = context.new_page()
    page.goto("https://cuttlefish.baidu.com/shopmis?_wkts_=1687423302076#/taskCenter/majorTask")
    time.sleep(99999)
    # Close page
    page.close()
    # ---------------------
    context.close()
    browser.close()


def runplay(num):
    pythoncom.CoInitialize()
    model_path = data['folderPath']
    name = zhanghaolist[num - 1]
    url = ''
    if name == 'A01A':
        url = "https://reg.justeasy.cn/User/model/modelupload.php"
        with sync_playwright() as playwright:
            run_A01A(playwright, num, url, name, model_path)
    elif name == 'A01B':
        url = "https://reg.justeasy.cn/User/d5model/modelupload.php"
        with sync_playwright() as playwright:
            run_A01B(playwright, num, url, name, model_path)
    elif name == 'A01C':
        url = "https://reg.justeasy.cn/User/sumodel/modelupload.php"

    elif name == 'A01D':
        url = "https://reg.justeasy.cn/User/tietu/tietupload.php"

    elif name == 'A01E':
        url = "https://reg.justeasy.cn/User/cad/cadupload.php"

    elif name == 'A02A':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"
        with sync_playwright() as playwright:
            run_A02A(playwright, num, url, name, model_path)
    elif name == 'A02B':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"
        with sync_playwright() as playwright:
            run_A02B(playwright, num, url, name, model_path)
    elif name == 'A02C':
        url = "https://cloud.shinewonder.com/user-center/static/html/index.html#/cloudModel/uploadModel"

    elif name == 'A03A':
        url = "https://www.cg99.com/models/create/model"
        with sync_playwright() as playwright:
            run_A03A(playwright, num, url, name, model_path)
    elif name == 'A04A':
        url = "https://www.cg6.com/plugin.php?id=cg6_down:t&ac=add"
        with sync_playwright() as playwright:
            run_A04A(playwright, num, url, name, model_path)
    elif name == 'A05A':
        url = "https://www.cgmxw.com/plugin.php?id=cg6_down:t&ac=add"
        with sync_playwright() as playwright:
            run_A05A(playwright, num, url, name, model_path)
    elif name == 'A06A':
        url = "https://www.cgmodel.com/works/model-publish-v.html"
        with sync_playwright() as playwright:
            run_A06A(playwright, num, url, name, model_path)
    elif name == 'A07A':
        url = "https://upload_file.3d66.com/upload/index/index"
        with sync_playwright() as playwright:
            run_A07A(playwright, num, url, name, model_path)
    elif name == 'A07B':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A07C':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A07D':
        url = "https://upload_file.3d66.com/upload/index/index"
    elif name == 'A08A':
        url = "https://www.om.cn/pusher/model"
        with sync_playwright() as playwright:
            run_A08A(playwright, num, url, name, model_path)
    elif name == 'A08B':
        url = "https://www.om.cn/pusher/model"
        with sync_playwright() as playwright:
            run_A08B(playwright, num, url, name, model_path)
    elif name == 'A08C':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A08D':
        url = "https://www.om.cn/pusher/model"
    elif name == 'A09A':
        url = "https://www.znzmo.com/creatorCenter/upload"
        with sync_playwright() as playwright:
            run_A09A(playwright, num, url, name, model_path)
    elif name == 'A09B':
        url = "https://www.znzmo.com/creatorCenter/upload"
        with sync_playwright() as playwright:
            run_A09B(playwright, num, url, name, model_path)
    elif name == 'A09C':
        url = "https://www.znzmo.com/creatorCenter/upload"
    elif name == 'A09D':
        url = "https://www.znzmo.com/creatorCenter/upload"
    else:
        print("编号错误，请重新输入")
        return


def getcookieplay():
    with sync_playwright() as playwright:
        getcookie(playwright)


def checkcookieplay(num):
    with sync_playwright() as playwright:
        checkcookie(playwright, num)


def get_json_files(folder_path):
    json_files = []
    for file_name in os.listdir(folder_path):
        if file_name.endswith('.json'):
            json_files.append(os.path.splitext(file_name)[0])  # 只保留文件名，不保留后缀
    return json_files


zhanghaolist = get_json_files("AccountData/AccountCookie")
zhanghaonum = len(zhanghaolist)
# 定义一个全局字典来跟踪账号的状态
account_status = {account: '等待运行' for account in zhanghaolist}

# 创建列表
lists = []
for i in range(zhanghaonum):
    table_name = "zhanghao" + str(i + 1)  # 加一使序号从1开始
    table = [i + 1, zhanghaolist[i]]  # 同样，这里的 i 也需要加一
    lists.append(table)
for table in lists:
    print(table)
zhanghaolist = get_json_files("AccountData/AccountCookie")


def main():
    thread = []
    if len(zhanghaolist) < 10:
        for i, file_name in enumerate(zhanghaolist, start=1):

            logging.info(f"启动线程{i}.，绑定网站ID为“{file_name}”")
            new_folder_path = os.path.join('output_logs', file_name)
            if not os.path.exists(new_folder_path):  # 如果file_name文件夹不存在，创建它
                os.makedirs(new_folder_path)
            k = threading.Thread(target=runplay, args=(i,))
            thread.append(k)
        for j in thread:
            j.daemon = True
            j.start()
            time.sleep(2)
        time.sleep(60)
        for t in thread:
            t.join()
    else:
        logging.error(f"账号数量超过限制，请删除一些cookie后再试 ")


def checkmain():
    thread = []
    if len(zhanghaolist) < 99:
        for i, file_name in enumerate(zhanghaolist, start=1):
            logging.info(f"启动线程{i}.，绑定账号为“{file_name}”")
            new_folder_path = os.path.join('output_logs', file_name)
            if not os.path.exists(new_folder_path):  # 如果file_name文件夹不存在，创建它
                os.makedirs(new_folder_path)
            k = threading.Thread(target=checkcookieplay, args=(i,))
            thread.append(k)
        for j in thread:
            j.daemon = True
            j.start()
        time.sleep(60)
        for t in thread:
            t.join()
    else:
        logging.error(f"'账号数量超过限制，请修改后再试' ")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    ex.show()
    sys.exit(app.exec_())
